<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="任务编号" prop="taskNum">
        <el-input
          v-model="queryParams.taskNum"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="省" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择省" @change="chooseProvince" clearable value-key="name">
           <el-option
                v-for="item in provinceData"
                :key="item.id"
                :label="item.name"
                :value="item">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择市" @change="chooseCity" clearable value-key="name">
           <el-option
                v-for="item in cityData"
                :key="item.id"
                :label="item.name"
                :value="item">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="区/县" prop="county">
        <el-select v-model="queryParams.county" placeholder="请选择区/县" @change="chooseArea" clearable value-key="name">
           <el-option
                v-for="item in areaData"
                :key="item.id"
                :label="item.name"
                :value="item">
            </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button plain icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="ypgResultList"  @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="任务编号" align="center" prop="taskNum" />
      <el-table-column label="任务名称" align="center" prop="taskName" >
      	<template #default="scope">
            <el-button type="text" @click="edit(scope.row)">{{
              scope.row.taskName
            }}</el-button>
      	</template>
    	</el-table-column>
      
      <el-table-column label="任务管理员" align="center" prop="taskManager" />
      <el-table-column label="承担小组" align="center" prop="groupName" />
      <el-table-column label="任务地区" align="center" prop="taskDistrict" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">   	         
          <el-button
            type="text"            
            @click="handleUpload(scope.row)"
          >上传</el-button>         
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.rows"
      @pagination="getList"
    />
		<!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <p></p>
        <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :before-upload="handleFileBeforeUpload"
            :on-progress="handleFileUploadProgress" :on-error="handleFileUploadError"
            :on-success="handleFileSuccess" :auto-upload="false" :data="dataFile" drag>
            <el-icon class="el-icon--upload">
                <upload-filled />
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
                <div class="el-upload__tip text-center">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" v-if="activeName=='first'" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('预评估结果模板-地市级行政区预评估结果统计表.xlsx')">下载模板</el-link>
                    <el-link type="primary" v-else :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate('预评估结果模板-附表1.预评估结果表.xlsx')">下载模板</el-link>
                </div>
            </template>
        </el-upload>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button plain @click="upload.open = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 添加或修改区县致死性差异性对话框 -->
    <el-dialog :title="title" v-model="open" width="1300px" append-to-body>
      
      	<p class="dialogTitle">{{taskNametitle}}</p>
 				<!--<el-row>
   				<el-col :span="12" style="margin-bottom: 20px;font-size: 20px;font-weight: bold;">	       		
	       			{{taskNametitle}}		          		        
	       </el-col>	       	
   			</el-row>-->
   			
   				<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
				    <el-tab-pane label="地市级行政区预评估结果统计表" name="first">
				    	<el-row :gutter="10" class="mb8">
			            <el-col :span="1.5">
			                <el-button type="primary" @click="handleImport">导入</el-button>
			            </el-col>
			        </el-row>
				    	<el-table v-loading="loading" :data="prefectureResult" border :span-method="objectSpanMethod">
					      <el-table-column label="地市、州" align="center" prop="city" />
					      <el-table-column label="震级" align="center" prop="magnitude" />
					      <el-table-column label="死亡人数（人）" align="center" prop="deathToll" />
					      <el-table-column label="受伤人数（人）" align="center" prop="injuredNum" />
					      <el-table-column label="需紧急安置人数（人）" align="center" prop="resettledNum"/>
					      <el-table-column label="需救援力量（人）" align="center" prop="rescueForce"/>
					      <el-table-column label="需帐篷数量（顶）" align="center" prop="tentNum"/>
					    </el-table>
				    </el-tab-pane>
				    <el-tab-pane label="附表1.预评估结果表" name="second">
				    	<el-row :gutter="10" class="mb8">
			            <el-col :span="1.5">
			                <el-button type="primary" @click="handleImport1">导入</el-button>
			            </el-col>
			            
			        </el-row>
				    	<el-table v-loading="loading" :data="Result" border  style="width: 100%" :span-method="objectSpanMethod1">
					      <el-table-column label="序号" align="center" prop="sort"/>
					      <el-table-column label="经度" align="center" prop="longitude" />
					      <el-table-column label="纬度" align="center" prop="latitude" />
					      <el-table-column label="宏观位置" align="center" width="120" prop="macroPosition" />
					      <el-table-column label="震级" align="center" width="120" prop="magnitude" />
					      
					      <el-table-column label="灾区面积（km²）" align="center" width="140" prop="disasterArea" />
					      <el-table-column label="灾区人口（万人）" align="center" width="140" prop="disasterNum" />
					      <el-table-column label="灾区GDP（亿）" align="center" width="140" prop="disasterGDP" />
					      <el-table-column label="预评估结果" align="center">
						      <el-table-column label="灾区经济损失（亿）" align="center" width="150" prop="disasterLoss" />
						      <el-table-column label="死亡人数（人）" align="center" width="140" prop="deathToll" />
						      <el-table-column label="受伤人数（人）" align="center" width="140" prop="injuredNum" />
						      <el-table-column label="需紧急安置人数（人）" align="center" width="170" prop="resettledNum"/>
						      <el-table-column label="需紧急救援力量（人）" align="center" width="170" prop="rescueForce"/>
						      <el-table-column label="预估需帐篷（顶）" align="center" width="140" prop="tentNum"/>
						    </el-table-column>
					      
					    </el-table>
				    </el-tab-pane>				    
				  </el-tabs>
  
      <template #footer>
        <div class="dialog-footer">          
          <el-button plain @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看弹出框 -->
    <el-dialog v-model="openDetail" title="查看任务" width="900px">
      <detailAssess :detilList="detailList" />
    </el-dialog>
  </div>
</template>

<script setup>
import { listypgResult, delypgResult, getPrefectureResult, getResult } from "@/api/resultManage/ypgResult";
import { getProvince, getChildArea} from "@/api/system/division";
import { detailTask } from '@/api/resultManag/reportCheck' 
import { getToken } from "@/utils/auth";
import useUserStore from '@/store/modules/user'
import detailAssess from "../../taskmanage/assess/detailAssess.vue";

const { proxy } = getCurrentInstance();
const activeName = ref('first');
const ypgResultList = ref([]);
const prefectureResult = ref([]);
const Result = ref([]);
const isCityEdit = ref(true);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const taskNametitle = ref("");
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]);//区、县

const provinceFormData = ref([]);//表单省 
const cityFormData = ref([]);//表单市
const areaFormData = ref([]);//表单区、县
const dataFile = reactive({
    taskCode: null,
})
/*** 用户导入参数 */
const upload = reactive({
    open: false,
    title: "",
    isUploading: false,
    headers: { token: "token " + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + "/result/uploadPrefectureResult"
});

const data = reactive({
  form: {},
  queryParams: {
    page: 1,
    rows: 10,
    taskNum: null,
    taskName: null,
    province: null,
    city: null,
    county: null
    
  },
  rules: {
    taskNum: [
      { required: true, message: "任务编号不能为空", trigger: "blur" }
    ],
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    province: [
      { required: true, message: "省不能为空", trigger: "blur" }
    ],
    provinceId: [
      { required: true, message: "省不能为空", trigger: "change" }
    ],
    city: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    cityId: [
      { required: true, message: "市不能为空", trigger: "blur" }
    ],
    area: [
      { required: true, message: "区/县不能为空", trigger: "blur" }
    ],
    areaId: [
      { required: true, message: "区/县 不能为空", trigger: "blur" }
    ],

  }
});

const { queryParams, form, rules } = toRefs(data);

function getList() {
  loading.value = true;
  listypgResult(queryParams.value).then(response => {
    ypgResultList.value = response.data.rows;;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 获取省列表 */
function getProvinceData() {
	getProvince().then(response => {
	    provinceData.value = response.data;
	});
}

function getProvinceFormData() {
	getProvince().then(response => {
	    provinceFormData.value = response.data;
	});
}

function chooseProvince(value){
	queryParams.value.city = null;
	queryParams.value.area = null;
	queryParams.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then(response => {
    cityData.value = response.data;
	});
//	provinceData.value.map(item => {//遍历数据
//		if(item.id == value){
//			if(item.name == "北京市"||item.name == "天津市"||item.name == "上海市"||item.name == "重庆市"){
//		    cityData.value.push(JSON.parse(JSON.stringify(item)));
//			}else{
//				getChildArea(value).then(response => {
//			    cityData.value = response.data;
//				});
//			}
//			return;
//		}   
//})		
}

function chooseCity(value){
	queryParams.value.county = null;
	queryParams.value.city = value.name;
	areaData.value = [];
	getChildArea(value.id).then(response => {
	    areaData.value = response.data;
	});
}
function chooseArea(value) {
  queryParams.value.county = value.name;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    modelName: null,
    province: null,
    provinceId: null,
    city: null,
    cityId: null,
    areaId: null,
    isDefault: null,
  };
  proxy.resetForm("ypgResultRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;  
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
	cityData.value = [];
	areaData.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/*上传*/
function handleUpload(row){
	reset();
	title.value = "预评估结果上传";
	taskNametitle.value = row.taskName;
	open.value = true;
	dataFile.taskCode = row.taskNum;
	getPrefectureResult(row.taskNum).then(response => {  	
    prefectureResult.value = response.data;
  });
  getResult(row.taskNum).then(response => {  	
    Result.value = response.data;
  });
  console.log(prefectureResult.value)
}

/** 查看按钮操作 */
const openDetail = ref(false)
const detailList = reactive({
  preAssessTaskEntity: {
    taskYear: undefined,
    taskNum: undefined,
    taskName: undefined,
    taskArea: undefined,
    taskRegion: undefined,
    districtList: undefined,
    groupName: undefined,
    groupLeader: undefined,
    taskDistrict: undefined,
  },
  expertlist: undefined,
  memberlist: "",
})
function edit(row) {
  console.log(row)
  detailTask({id: row.id}).then(response => {
    if(response.code == 200){
      openDetail.value = true
      nextTick(() => {
        detailList.preAssessTaskEntity = response.data.preAssessTaskEntity
        detailList.memberlist = response.data.memberlist
        detailList.expertlist = response.data.expertlist
      })
    }
  })
//reset();
//const id = row.id 
//if(row.isDefault=="1"){
//	isCopy.value = true;
//	Default.value = "1";
//	title.value = "系统默认需安置人员计算模型";
//}else{
//	isCopy.value = false;
//	Default.value = "0";
//	title.value = "需安置人员计算模型";
//}
//
//getModelypgResult(id).then(response => {
//	
//  form.value = response.data;
//  
//  open.value = true;
//  if(form.value.city=="全部"){
//  	radio.value = "1"
//  }else{
//  	radio.value = "2"
//  	isCityEdit.value = false
//  }
//  if(form.value.isDefault=="0"){
//  	isEditDefault.value = true
//  }else{
//  	isEditDefault.value = false
//  }
//  
//});
}

/*切换标签页*/
function handleClick(tab, event) {
	console.log(tab.props.name);
	if(tab.props.name=="first"){
		upload.url = import.meta.env.VITE_APP_BASE_API + "/result/uploadPrefectureResult"
	}else{
		upload.url = import.meta.env.VITE_APP_BASE_API + "/result/uploadResult"
	}
}

// 模板下载
function importTemplate(name) {
  proxy.download("/base/product/downloadExcel", {
    fileName:name
  }, name);
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 打开导入表弹窗 */
function handleImport() {
    upload.title = "导入";
    if(prefectureResult.value.length!=0){
    	proxy.$modal.confirm('重新导入会全部覆盖').then(() => {
			   upload.open = true;
			}).catch(() => {});    	
    }else{
    	upload.open = true;
    }
}

/** 打开导入表弹窗 */
function handleImport1() {
    upload.title = "导入";
    if(Result.value.length!=0){
    	proxy.$modal.confirm('重新导入会全部覆盖').then(() => {
			   upload.open = true;
			}).catch(() => {});
    }else{
    	upload.open = true;
    }
}

/**文件上传前处理 */
function handleFileBeforeUpload(file) {
    proxy.$modal.loading("正在导入文件，请稍候...");
    return true
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
// 上传失败
function handleFileUploadError(err) {
	console.log("22")
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("导入文件失败");
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$modal.closeLoading();
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 0 0;'>" + response.message + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getPrefectureResult(dataFile.taskCode).then(response => {  	
    prefectureResult.value = response.data;
  });
  getResult(dataFile.taskCode).then(response => {  	
    Result.value = response.data;
  });
};
function objectSpanMethod({ row, column, rowIndex, columnIndex }) {
	 if (columnIndex === 0) {
		 const _row = setTable(prefectureResult.value).one[rowIndex];
		 const _col = _row > 0 ? 1 : 0;
		 return {
			 rowspan: _row,
			 colspan: _col
		 };
	 }
//	 if (columnIndex === 1 ) {
//		 const _row = setTable(getData.value).two[rowIndex];
//		 const _col = _row > 0 ? 1 : 0;
//		 return {
//		 rowspan: _row,
//			 colspan: _col
//			};
//		}
//	 if (columnIndex === 3 ) {
//		 const _row = setTable(getData.value).three[rowIndex];
//		 const _col = _row > 0 ? 1 : 0;
//		 return {
//		 rowspan: _row,
//			 colspan: _col
//			};
//		}
//	 if (columnIndex === 4 ) {
//		 const _row = setTable(getData.value).four[rowIndex];
//		 const _col = _row > 0 ? 1 : 0;
//		 return {
//		 rowspan: _row,
//			 colspan: _col
//			};
//		}
}

function objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
	 if (columnIndex === 0) {
		 const _row = setTable1(Result.value).one[rowIndex];
		 const _col = _row > 0 ? 1 : 0;
		 return {
			 rowspan: _row,
			 colspan: _col
		 };
	 }
	 if (columnIndex === 1 ) {
		 const _row = setTable1(Result.value).two[rowIndex];
		 const _col = _row > 0 ? 1 : 0;
		 return {
		 rowspan: _row,
			 colspan: _col
			};
		}
	 if (columnIndex === 2 ) {
		 const _row = setTable1(Result.value).three[rowIndex];
		 const _col = _row > 0 ? 1 : 0;
		 return {
		 rowspan: _row,
			 colspan: _col
			};
		}
	 if (columnIndex === 3 ) {
		 const _row = setTable1(Result.value).four[rowIndex];
		 const _col = _row > 0 ? 1 : 0;
		 return {
		 rowspan: _row,
			 colspan: _col
			};
		}
}
function setTable(tableData) {
	 let spanOneArr = [],
	 spanTwoArr = [],
	 spanThreeArr = [],
	 spanFourArr = [],
	 concatOne = 0,
	 concatTwo = 0,
	 concatThree = 0,
	 concatFour = 0;
	 tableData.forEach((item, index) => {
		 if (index === 0) {
			 spanOneArr.push(1);
			 spanTwoArr.push(1);
			 spanThreeArr.push(1);
			 spanFourArr.push(1);
		 } else {
			 if (item.city === tableData[index - 1].city) {
			 //第一列需合并相同内容的判断条件
				 spanOneArr[concatOne] += 1;
				 spanOneArr.push(0);
			 } else {
				 spanOneArr.push(1);
				 concatOne = index;
			 }
			 
//			 if (item.longitude === tableData[index - 1].longitude) {
//			 //第二列和需合并相同内容的判断条件
//				 spanTwoArr[concatTwo] += 1;
//				 spanTwoArr.push(0);
//			 } else {
//				 spanTwoArr.push(1);
//				 concatTwo = index;
//			 }
//			 
//			 if (item.latitude === tableData[index - 1].latitude) {
//			 //第三列和需合并相同内容的判断条件
//				 spanThreeArr[concatThree] += 1;
//				 spanThreeArr.push(0);
//			 } else {
//				 spanThreeArr.push(1);
//				 concatThree = index;
//			 }
//			 
//			 if (item.macroPosition === tableData[index - 1].macroPosition) {
//			 //第三列和需合并相同内容的判断条件
//				 spanFourArr[concatFour] += 1;
//				 spanFourArr.push(0);
//			 } else {
//				 spanFourArr.push(1);
//				 concatFour = index;
//			 }
		 }
	 });
 	return {
		 one: spanOneArr,
		 two: spanTwoArr,
		 three: spanThreeArr,
		 four: spanFourArr,
 	};
}
function setTable1(tableData) {
	 let spanOneArr = [],
	 spanTwoArr = [],
	 spanThreeArr = [],
	 spanFourArr = [],
	 concatOne = 0,
	 concatTwo = 0,
	 concatThree = 0,
	 concatFour = 0;
	 tableData.forEach((item, index) => {
		 if (index === 0) {
			 spanOneArr.push(1);
			 spanTwoArr.push(1);
			 spanThreeArr.push(1);
			 spanFourArr.push(1);
		 } else {
			 if (item.sort === tableData[index - 1].sort && index % item.rowNum!=0) {
			 //第一列需合并相同内容的判断条件
				 spanOneArr[concatOne] += 1;
				 spanOneArr.push(0);
			 } else {
				 spanOneArr.push(1);
				 concatOne = index;
			 }
			 
			 if (item.longitude === tableData[index - 1].longitude && index % item.rowNum!=0) {
			 //第二列和需合并相同内容的判断条件
				 spanTwoArr[concatTwo] += 1;
				 spanTwoArr.push(0);
			 } else {
				 spanTwoArr.push(1);
				 concatTwo = index;
			 }
			 
			 if (item.latitude === tableData[index - 1].latitude && index % item.rowNum!=0) {
			 //第三列和需合并相同内容的判断条件
				 spanThreeArr[concatThree] += 1;
				 spanThreeArr.push(0);
			 } else {
				 spanThreeArr.push(1);
				 concatThree = index;
			 }
			 
			 if (item.macroPosition === tableData[index - 1].macroPosition && index % item.rowNum!=0) {
			 //第三列和需合并相同内容的判断条件
				 spanFourArr[concatFour] += 1;
				 spanFourArr.push(0);
			 } else {
				 spanFourArr.push(1);
				 concatFour = index;
			 }
		 }
	 });
 	return {
		 one: spanOneArr,
		 two: spanTwoArr,
		 three: spanThreeArr,
		 four: spanFourArr,
 	};
}
getList();
getProvinceData();
getProvinceFormData();
</script>
<style lang="scss" scoped>
:deep(.el-table) td.el-table__cell {
    border-bottom: 1px solid #ebeef5 !important;
    border-right: 1px solid #ebeef5 !important;
}
</style>
